package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.li.work.mapper.SysDeptMapper;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.teaching.domain.PlatformQKnowledge;
import com.ruoyi.teaching.domain.UniversalCreateUpdate;
import com.ruoyi.teaching.domain.vo.PlatformQKnowledgeVO;
import com.ruoyi.teaching.mapper.PlatformQKnowledgeMapper;
import com.ruoyi.teaching.service.PlatformQKnowledgeService;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2024-06-11
 */
@Service
public class PlatformQKnowledgeServiceImpl extends ServiceImpl<PlatformQKnowledgeMapper, PlatformQKnowledge> implements PlatformQKnowledgeService {
    @Autowired
    private PlatformQKnowledgeMapper platformQKnowledgeMapper;

    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public AjaxResult selectPlatformQKnowledgeById(Long id) {
        PlatformQKnowledge platformQKnowledge = platformQKnowledgeMapper.selectById(id);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformQKnowledge);
    }


    @Override
    public AjaxResult selectPlatformQKnowledgeListInExam() {
        List<PlatformQKnowledgeVO> platformQKnowledge = getKnowledgeListBySpecialtyId();
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformQKnowledge);
    }

    private List<PlatformQKnowledgeVO> getKnowledgeListBySpecialtyId() {
        Long userId = SecurityUtils.getUserId();
        Long deptId = sysUserMapper.selectUserById(userId).getMajorId();
        String specialtyName = deptMapper.selectDeptById(deptId).getDeptName();

        // 查询所有学校当前专业下的知识点
        Long[] deptIds = deptMapper.selectDeptIdByName(specialtyName);
        List<PlatformQKnowledgeVO> platformQKnowledges = platformQKnowledgeMapper.selectKnowledgeListBySpecialtyId(deptIds);
        // 使用 Java 流去重
        Map<String, PlatformQKnowledgeVO> uniqueKnowledgeMap = platformQKnowledges.stream()
                .collect(Collectors.toMap(
                        PlatformQKnowledgeVO::getKnowledgeName,
                        p -> p,
                        (existing, replacement) -> existing // 如果有重复的 knowledgeName，保留第一个出现的
                ));

        platformQKnowledges = uniqueKnowledgeMap.values().stream().collect(Collectors.toList());
        // 按照 createTime 降序排序
        platformQKnowledges.sort(Comparator.comparing(PlatformQKnowledgeVO::getCreateTime).reversed());
        return platformQKnowledges;
    }

    @Override
    public AjaxResult selectPlatformQKnowledgeListInQuestion() {
        List<PlatformQKnowledgeVO> platformQKnowledge = getKnowledgeListBySpecialtyId();
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformQKnowledge);
    }

    @Override
    public AjaxResult insertPlatformQKnowledge(PlatformQKnowledge platformQKnowledge) {
        UniversalCreateUpdate person = UniversalUtil.getCreateUpdate(sysUserMapper);
        String knowledgeName = platformQKnowledge.getKnowledgeName();
        Integer specialtyId = platformQKnowledge.getSpecialtyId();

        // 校验同一专业下是否存在相同的知识点名称
        PlatformQKnowledge existingKnowledge = platformQKnowledgeMapper.selectByNameAndSpecialty(knowledgeName, specialtyId);
        if (existingKnowledge != null && !existingKnowledge.getId().equals(platformQKnowledge.getId())) {
            return new AjaxResult(HttpStatus.ERROR, "在同一专业下已存在相同名称的知识点");
        }

        if (platformQKnowledge.getId() == null) {
            platformQKnowledge.setCreateTime(DateUtils.getNowDate());
            platformQKnowledge.setCreateId(person.getId());
            platformQKnowledge.setCreateBy(person.getName());
            int insert = platformQKnowledgeMapper.insert(platformQKnowledge);
            if (insert > 0) {
                return new AjaxResult(HttpStatus.SUCCESS, "新增成功");
            } else {
                return new AjaxResult(HttpStatus.ERROR, "新增失败");
            }
        } else {
            Long userId = SecurityUtils.getUserId();
            PlatformQKnowledge platformQKnowledge1 = platformQKnowledgeMapper.selectById(platformQKnowledge.getId());
            if (platformQKnowledge1 == null) {
                return new AjaxResult(HttpStatus.ERROR, "该知识点已被删除，请刷新后重试");
            }
            long l = platformQKnowledge1.getCreateId().longValue();
            if (l != userId) {
                return new AjaxResult(HttpStatus.ERROR, "无法修改他人创建的知识点");
            }
            platformQKnowledge.setUpdateTime(DateUtils.getNowDate());
            platformQKnowledge.setUpdateId(person.getId());
            platformQKnowledge.setUpdateBy(person.getName());
            int update = platformQKnowledgeMapper.updateById(platformQKnowledge);
            if (update > 0) {
                return new AjaxResult(HttpStatus.SUCCESS, "修改成功");
            } else {
                return new AjaxResult(HttpStatus.ERROR, "修改失败");
            }
        }
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deletePlatformQKnowledgeByIds(Long[] ids) {
        int i = 0;
        for (Long id : ids) {
            i++;
            long l = platformQKnowledgeMapper.selectById(id).getCreateId().longValue();
            Long userId = SecurityUtils.getUserId();
            if(l != userId){
                if(i == 1){
                    return new AjaxResult(HttpStatus.ERROR, "无法删除他人创建的知识点");
                }else {
                    return new AjaxResult(HttpStatus.ERROR, "删除失败，请核对第"+i+"条知识点是否是您的创建");
                }
            }
        }
        int length = ids.length;
        int delete = platformQKnowledgeMapper.deleteBatchIds(Arrays.asList(ids));
        if (length == delete) {
            return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
        } else {
            throw new RuntimeException("删除失败");
        }
    }
}
